#!/usr/bin/env bash
set -eu

source $SNAP/actions/common/utils.sh

use_snap_env

snapctl stop ${SNAP_NAME}.daemon-kubelite 2>&1 || true

# Try to symlink /var/lib/kubelet so that most kubelet device plugins work out of the box.
if test -L /var/lib/kubelet; then
  unlink /var/lib/kubelet || true
fi

# Try to symlink /var/lib/calico so that the Calico CNI plugin picks up the mtu configuration.
if test -L /var/lib/calico; then
  unlink /var/lib/calico || true
fi

# Try to symlink standard CNI Kubernetes directories.
if test -L /etc/cni/net.d; then
  unlink /etc/cni/net.d || true
fi
if test -L /opt/cni/bin; then
  unlink /opt/cni/bin || true
fi

pod_cidr="$(cat $SNAP_DATA/args/kube-proxy | grep "cluster-cidr" | tr "=" " "| gawk '{print $2}')"
if [ -z "$pod_cidr" ]
then
  pod_cidr="$(cat $SNAP_DATA/args/kubelet | grep "pod-cidr" | tr "=" " "| gawk '{print $2}')"
  if [ -z "$pod_cidr" ]
  then
    pod_cidr="$(jq .Network $SNAP_DATA/args/flannel-network-mgr-config | tr -d '\"')"
  fi
fi
if ! [ -z "$pod_cidr" ]
then
  iptables -D FORWARD -s "$pod_cidr" -m comment --comment "generated for MicroK8s pods" -j ACCEPT || true
  iptables -D FORWARD -d "$pod_cidr" -m comment --comment "generated for MicroK8s pods" -j ACCEPT || true
  iptables-nft -D FORWARD -s "$pod_cidr" -m comment --comment "generated for MicroK8s pods" -j ACCEPT || true
  iptables-nft -D FORWARD -d "$pod_cidr" -m comment --comment "generated for MicroK8s pods" -j ACCEPT || true
  iptables-legacy -t nat -F CNI-HOSTPORT-DNAT || true
fi

snapctl stop ${SNAP_NAME}.daemon-containerd 2>&1 || true
# wait for containerd to stop its processes or we will be getting a umount error
# because the mount points are busy
sleep 10

if ! is_strict
then
  # remove custom sysctl parameters
  rm -f /etc/sysctl.d/10-microk8s.conf
  sysctl --system

  rm -rf /etc/systemd/system/snap.microk8s.daemon-kubelite.service.d || true
fi

# Clean the container location so we do not snapshot it.
rm -rf ${SNAP_COMMON}/var/lib/containerd/* || true
rm -rf ${SNAP_COMMON}/run/containerd/* || true

(cat /proc/mounts | grep ${SNAP_COMMON}/var/lib/kubelet/pods | cut -d ' ' -f 2 | xargs umount -l) || true
# in case this is a pre root-dir fix deployment
(cat /proc/mounts | grep ${SNAP_COMMON}/pods | cut -d ' ' -f 2 | xargs umount -l) || true
(cat /proc/mounts | grep ${SNAP_COMMON}/var/lib/containerd | cut -d ' ' -f 2 | xargs umount -l) || true
(cat /proc/mounts | grep ${SNAP_COMMON}/run/containerd | cut -d ' ' -f 2 | xargs umount) || true
(cat /proc/mounts | grep ${SNAP_COMMON}/var/lib/docker | cut -d ' ' -f 2 | xargs umount -l) || true
(cat /proc/mounts | grep ${SNAP_COMMON}/var/run/docker | cut -d ' ' -f 2 | xargs umount) || true
(cat /proc/mounts | grep ${SNAP_COMMON}/var/lib/kubelet | cut -d ' ' -f 2 | xargs umount) || true

# Run remove hooks
$SNAP/usr/bin/python3 $SNAP/scripts/run-lifecycle-hooks.py remove || true
